package site.mingdao.boot.common.util.jwt;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.BadJWTException;
import site.mingdao.boot.common.util.number.NumberUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

public class JWTUtils {

    private String getToken(Long userId, String secret, String issuer, long time) throws JOSEException {
        JWSHeader jwsHeader = new JWSHeader
                .Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT)
                .build();
        Date now = new Date();
        Date expiresAt = new Date(now.getTime() / 1000 * 1000 + time);
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .issuer(issuer)
                .subject(userId.toString())
                .jwtID(UUID.randomUUID().toString())
                .issueTime(now)
                .expirationTime(expiresAt)
                .build();
        JWSSigner jwsSigner = new MACSigner(secret);
        SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
        signedJWT.sign(jwsSigner);
        return signedJWT.serialize();
    }

    private Long parseToken(String token, String secret) throws BadJWTException, ParseException, JOSEException {
        SignedJWT jwt = SignedJWT.parse(token);
        JWSVerifier jwsVerifier = new MACVerifier(secret);
        if (!jwt.verify(jwsVerifier)) {
            throw new BadJWTException("token invalid");
        }
        JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();
        if (jwtClaimsSet.getExpirationTime().getTime() < new Date().getTime()) {
            throw new BadJWTException("token expired");
        }
        return NumberUtils.parseLong(jwtClaimsSet.getSubject());
    }


}
